package com.jeasonzhao.web;

import javax.servlet.ServletRequest;

import com.jeasonzhao.commons.utils.Algorithms;
import com.jeasonzhao.commons.utils.ConvertEx;

public class ServletHelper
{
    public static final String NAMESEP="_____";
    private static final String NAMECONTROLID_SUFFIX = NAMESEP+"name";
    private ServletHelper()
    {
        super();
    }
    public static final String getNameControlId(String s)
    {
        if(null == s || s.trim().length() < 1 || s.trim().toLowerCase().endsWith(NAMECONTROLID_SUFFIX))
        {
            return null;
        }
        else
        {
            return s.trim() + NAMECONTROLID_SUFFIX;
        }
    }

    public static final boolean isNameControlId(String s)
    {
        if(null == s || s.trim().length() < 1 || s.trim().toLowerCase().endsWith(NAMECONTROLID_SUFFIX))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public static int getParameterInt(ServletRequest request,String ...keys)
    {
        return ConvertEx.toInt(getParameter(request,keys));
    }

    public static java.util.Date getParameterDate(ServletRequest request,String ...keys)
    {
        return ConvertEx.toDate(getParameter(request,keys));
    }

    public static String getParameterString(ServletRequest request,String ...keys)
    {
        return Algorithms.toString(getParameter(request,keys));
    }

    public static int getParameterInt(ServletRequest request,int valuedefault,String ...keys)
    {
        return ConvertEx.toInt(getParameter(request,keys),valuedefault);
    }

    public static double getParameterDouble(ServletRequest request,String ...keys)
    {
        return ConvertEx.toDouble(getParameter(request,keys));
    }

    public static double getParameterDouble(ServletRequest request,double valuedefault,String ...keys)
    {
        return ConvertEx.toDouble(getParameter(request,keys),valuedefault);
    }

    public static boolean containsParameter(ServletRequest request,String ...keys)
    {
        return null != (Object) getParameter(request,keys);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getParameter(ServletRequest request,String ...keys)
    {
        Object obj = null;
        if(null != keys)
        {
            for(String k : keys)
            {
                obj = innerGetParameter(request,k);
                if(null != obj)
                {
                    break;
                }
            }
        }
        return(T) obj;
    }

    public static String[] getParameters(ServletRequest request,String ...keys)
    {
        if(null != keys)
        {
            for(String k : keys)
            {
                String[] obj = innerGetParameters(request,k);
                if(null != obj)
                {
                    return obj;
                }
            }
        }
        return null;
    }

    private static String[] innerGetParameters(ServletRequest request,String strKey)
    {
        if(null == request || null == strKey || strKey.trim().length() < 1)
        {
            return null;
        }
        strKey = strKey.trim();
        try
        {
            String[] ret = request.getParameterValues(strKey);
            if(null == ret)
            {
                java.util.Enumeration<String> er = request.getParameterNames();

                while(er.hasMoreElements())
                {
                    String strTag = er.nextElement();
                    if(strKey.equalsIgnoreCase(strTag))
                    {
                        ret = request.getParameterValues(strKey);
                        return ret;
                    }
                }
                er = request.getAttributeNames();
                while(er.hasMoreElements())
                {
                    String strTag = er.nextElement();
                    if(strKey.equalsIgnoreCase(strTag))
                    {
                        Object obj = request.getAttribute(strTag);
                        return new String[]
                            {Algorithms.toString(obj)};
                    }
                }
                return null;
            }
            else
            {
                return ret;
            }
        }
        catch(Exception exce)
        {
            return null;
        }
    }

    private static Object innerGetParameter(ServletRequest request,String strKey)
    {
        if(null == request || null == strKey || strKey.trim().length() < 1)
        {
            return null;
        }
        strKey = strKey.trim();
        try
        {
            String ret = request.getParameter(strKey);
            if(null == ret)
            {
                java.util.Enumeration<String> er = request.getParameterNames();

                while(er.hasMoreElements())
                {
                    String strTag = er.nextElement();
                    if(strKey.equalsIgnoreCase(strTag))
                    {
                        ret = request.getParameter(strTag);
                        return ret;
                    }
                }
                er = request.getAttributeNames();
                while(er.hasMoreElements())
                {
                    String strTag = er.nextElement();
                    if(strKey.equalsIgnoreCase(strTag))
                    {
                        Object obj = request.getAttribute(strTag);
                        return obj;
                    }
                }
                return null;
            }
            else
            {
                return ret;
            }
        }
        catch(Exception exce)
        {
            return null;
        }
    }

    public static String combineUrl(String strInitUrl,String ...params)
    {
        if(Algorithms.isEmpty(strInitUrl))
        {
            return strInitUrl;
        }
        boolean isContain = strInitUrl.indexOf("?") > 0;
        for(int n = 0;null != params && n + 1 < params.length;n += 2)
        {
            if(null != params[n] && null != params[n + 1])
            {
                if(isContain == false)
                {
                    isContain = true;
                    strInitUrl += "?" + params[n] + "=" + params[n + 1];
                }
                else
                {
                    strInitUrl += "&" + params[n] + "=" + params[n + 1];
                }
            }
        }
        return strInitUrl;
    }

    public static String escape(String str)
    {
        if(Algorithms.isEmpty(str))
        {
            return str;
        }
        return str.replaceAll("\"","\\\\\"")
            .replaceAll("\r","\\\\r")
            .replaceAll("\n","\\\\n");
    }

    public static String escapeRegex(String str)
    {
        if(Algorithms.isEmpty(str))
        {
            return str;
        }
        return str.replaceAll("\\x5c","\\\\\\\\");
    }

    public static String exception2HTML(Throwable ex,Class<?> cls)
    {
        if(null == ex)
        {
            return null;
        }
        StringBuffer buf = new StringBuffer();
        buf.append("<div class=\"tagexception\">");
        buf.append("<div class=\"message\"><center><b>TagLib ERROR</b>");
        if(null != cls)
        {
            buf.append("<br/>From " + cls.getName() + "");
        }
        buf.append("</center></div>");
        buf.append("<div class=\"message\">" + ex.getMessage() + "</div>");
        if(null != ex.getCause())
        {
            buf.append("<div class=\"message\">" + ex.getCause().getMessage() + "</div>");
        }
        showStackTrace(buf,ex);
        buf.append("</div>");
        return buf.toString();
    }

    private static void showStackTrace(StringBuffer buf,Throwable ex)
    {
        for(StackTraceElement e : ex.getStackTrace())
        {
            if(e.getClassName().startsWith("javax.servlet.")
               || e.getClassName().startsWith("org.apache.")
               || e.getClassName().startsWith("java.lang.")
                )
            {
                continue;
            }
            buf.append("<div class=\"trace\">" + e.getClassName() + ":" + e.getLineNumber() + "</div>");
        }
        if(null != ex.getCause())
        {
            showStackTrace(buf,ex.getCause());
        }
    }

}
